package com.yrh.dao.impl;

import com.yrh.bean.TProduct;
import com.yrh.dao.TProductDao;
import com.yrh.utils.DataSourceUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
/*菜品信息数据层接口实现类*/
public class TProductDaoImpl implements TProductDao {
    private JdbcTemplate temp=new JdbcTemplate(DataSourceUtil.getDataSource());
    /*查询所有含分页*/
    @Override
    public List<TProduct> allProduct(TProduct tProduct,int nowPage,int size) {
        String sql="select p.*,c.category_name\n" +
                "from t_product p,t_category c\n" +
                "where p.category_id=c.category_id ";
        List<String> list=new ArrayList<>();
        if (tProduct.getCategoryName()!=null&&!"".equals(tProduct.getCategoryName())){
            sql += " and category_name = ?";
            list.add(tProduct.getCategoryName());
        }
        if (tProduct.getProductName()!=null&&!"".equals(tProduct.getProductName())){
            sql += " and  product_name like ? ";
            list.add("%"+tProduct.getProductName()+"%");
        }
        if (size!=0){
            sql+=" limit "+(nowPage-1)*size+","+size;
        }
        return temp.query(sql,list.toArray(),new BeanPropertyRowMapper<>(TProduct.class));
    }
    //查找菜品名
    @Override
    public TProduct byPName(TProduct tProduct) {
        try {
            return temp.queryForObject("SELECT * FROM t_product WHERE product_name=?",new BeanPropertyRowMapper<>(TProduct.class)
            ,tProduct.getProductName());
        } catch (Exception e) {
           return null;
        }
    }
    //添加或修改方法
    @Override
    public int updateProduct(TProduct product) {
        Object [] objects=new Object[]{
           product.getProductName(),
           product.getProductPic(),
           product.getProductPrice(),
           product.getProductDescribe(),
           product.getCategoryId()
        };
        if (product.getProductId()==0){
            return temp.update("INSERT INTO t_product(product_name,product_pic,product_price,product_describe,category_id)" +
                    " VALUES(?,?,?,?,?)",objects);
        }
        else return temp.update("update t_product set product_name=?,product_pic=?,product_price=?,product_describe=?,category_id=? where product_id=?",product.getProductName(),product.getProductPic(),product.getProductPrice(),product.getProductDescribe(),product.getCategoryId(),product.getProductId());
    }
   /*删除方法*/
    @Override
    public int delProduct(TProduct product) {
        return temp.update("delete from t_product where product_id=?",product.getProductId());
    }
    //修改状态
    @Override
    public int updateStatus(TProduct product) {
        return temp.update("update t_product set product_status=? where product_id=?",product.getProductStatus(),product.getProductId());
    }
}
